<template>
  <div class="card-box">
    <PubTable
      :tableData="crudData"
      :uploadUrl="uploadUrl"
      @selected-items="getSelection"
    />
  </div>
</template>

<script lang="jsx" setup>
defineOptions({ name: "deviceList" });
import "@/components/PubTable/style/pubTablecss.scss";
import {
  tableData as mockData,
  caserData,
} from "@/components/PubTable/utils/mockData.js";
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
let { proxy } = getCurrentInstance();
import { useRouter } from "vue-router";
import "@/utils/common.js";

const router = useRouter();
const isDetail = ref(false);

const productList = ref([]);
//只能输入数字
function validateNumberOnly(rule, value, callback) {
  const reg = /^\d+$/;
  if (!reg.test(value)) {
    callback(new Error("只能输入数字"));
  } else {
    callback();
  }
}
const editId = ref();
//全局数据配置
const crudData = ref({
  clums: [
    // {
    //   type: "selection",
    //   width: 40,
    //   label: "复选框",
    //   fixed: "left",
    // },
    {
      type: "index",
      props: "index",
      label: "序号",
      width: 80,
      fixed: "left",
    },
    {
      props: "status",
      label: "设备状态",
      render: (scope) => {
        if(scope.row.status == 0)
        {
          return (
          <>  <div  class="public-left txt-normal">在线</div></>);
        }
        else if(scope.row.status == 1)
        {
          return (
          <>  <div  class=" public-left txt-offline">离线</div></>);
        }
        else if(scope.row.status == 2)
        {
          return (
          <>  <div  class=" public-left txt-break">故障</div></>);
        }
        else if(scope.row.status == 3)
        {
          return (
          <>  <div  class=" public-left txt-alarm">报警</div></>);
        }
          
        
      },
    },
    {
      props: "equimentName",
      label: "设备名称",
      search: {
        key: "equipmentName",
        type: "input",
        placeholder: "搜索设备名称",
        minWidth: "200px",
        clearable: true,
        maxLength: 20,
      },
    },
    {
      props: "address",
      label: "地址码",
    },
    {
      props: "netType",
      label: "连网类型",
      minWidth: "100px",
      search: {
        key: "netType",
        type: "select",
        placeholder: "连网类型",
        clearable: true,
        maxLength: 20,
        optionList: [
          {
            label: "串口",
            value: "串口",
          },
          {
            label: "BLE",
            value: "BLE",
          },
          {
            label: "2/3/4G",
            value: "2/3/4G",
          },
          {
            label: "WIFI",
            value: "WIFI",
          },
          {
            label: "NB",
            value: "NB",
          },
          {
            label: "LoRa",
            value: "LoRa",
          },
        ],
      },
    },
    {
      props: "productName",
      label: "所属产品",
    },
    {
      props: "createTime",
      label: "创建时间",
      minWidth: "100px",
      search: {
        key: "createTime",
        type: "timerange",
        startPlaceholder: "选择创建时间",
        endPlaceholder: "选择创建时间",
        separator: "至",
        clearable: true,
        maxLength: 20,
        timeFormatter: "YYYY-MM-DD HH:mm:ss",
      },
    },
    {
      props: "caozuo",
      label: "操作",
      width: 150,
      fixed: "right",
      render: (scope) => {
        return (
          <>
            <span
              class="p-table-btn p-table-btn-b"
              onClick={() => {
                let rowInfo = JSON.stringify(scope.row);
                router.push({
                  path: "/deviceListDetail",
                  query: {
                    detailInfo: rowInfo,
                  },
                });
              }}
            >
              详情
            </span>
            <span
              class="p-table-btn p-table-btn-b"
              onClick={async () => {
                crudData.value.form.formName = "编辑";
                editId.value = scope.row.id;

                crudData.value.form.formList = crudData.value.form.formList.map(
                  (item) => {
                    item.value = scope.row[item.key] || null;
                    return item;
                  }
                );

                crudData.value.form.formShow = true;
              }}
            >
              编辑
            </span>
            <span
              class="p-table-btn p-table-btn-r"
              onClick={() => {
                ElMessageBox.confirm(
                  "删除后系统无法恢复，确认删除吗?",
                  "信息提示",
                  {
                    confirmButtonText: "确认",
                    cancelButtonText: "取消",
                    customClass: "public-message-box-default",
                  }
                ).then(() => {
                  //删除逻辑
                  proxy
                    ._http({
                      url: "/api/equipment/delete",
                      type: "post",
                      isBody: true,
                      isLoading: true,
                      data: {
                        id: scope.row.id,
                      },
                    })
                    .then((res) => {
                      ElMessage.success("删除成功");
                      getTableData();
                    })
                    .catch((err) => {});
                });
              }}
            >
              删除
            </span>
          </>
        );
      },
    },
  ],
  handleBtns: [
    {
      text: "下载设备数据",
      onClick: () => {
          console.log("下载数据")
           proxy
            ._http({
              url: "/api/download",
              type: "post",
              isBlob: true,
              isLoading: true,
            })
            .then((res) => {
              console.log("下载：",res);
              handleFileDownload(res.data,res);
            })
      },
    },
    {
      text: "添加",
      onClick: () => {
        crudData.value.form.formName = "添加";
        crudData.value.form.formList = crudData.value.form.formList.map(
          (item) => {
            if (item.type == "multSelect") {
              item.value = [];
            } else {
              item.value = null;
            }
            return item;
          }
        );
        crudData.value.form.formShow = true;

        // showAdd.value = true;
      },
    },
    {
      text: "删除设备数据",
      onClick: () => {
         ElMessageBox.confirm(
          "删除后系统无法恢复，确认删除吗?",
          "信息提示",
          {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            customClass: "public-message-box-default",
          }
        ).then(() => {
          //删除逻辑
          proxy
            ._http({
              url: "/api/systemConfig/devdelete",
              type: "post",
              isBody: true,
              isLoading: true,
            })
            .then((res) => {
              ElMessage.success("删除成功");
            })
            .catch((err) => {});
        });
      },
    },
  ],
  // sortRule 默认排序规则,排序字段prop在 clums中加上sortable
  sortRule: { prop: "value3", order: "descending" }, // prop: 'value3', order: 'descending'||'ascending'
  // data 获取数据getTableData
  data: mockData,
  // pager 分页配置
  pager: {
    total: 11,
    pageIndex: 1,
    pageSize: 10,
    pagerLang: [10, 20, 50, 100],
    sizeChange: (e) => {
      // 改变每页条数
      crudData.value.pager.pageSize = e;
      crudData.value.pager.pageIndex = 1;
      getTableData();
    },
    pageIndexChange: (e) => {
      // 改变页码
      crudData.value.pager.pageIndex = e;
      getTableData();
    },
  },
  // form 弹窗配置 可自定义或直接配置
  form: {
    formName: "添加",
    formShow: false,
    formList: [
      {
        key: "equimentName",
        type: "input",
        label: "设备名称",
        placeholder: "请输入设备名称",
        maxLength: 20,
        validate: [
          {
            required: true,
            message: "请输入设备名称",
            trigger: "blur",
          },
        ],
      },
      {
        key: "address",
        type: "input",
        label: "地址码",
        placeholder: "请输入",
        maxLength: 20,
        validate: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
          //限制数字
          { validator: validateNumberOnly, trigger: "change" },
        ],
      },
      {
        key: "netType",
        type: "select",
        label: "连网类型",
        placeholder: "请选择连网类型",
        validate: [
          {
            required: true,
            message: "请选择连网类型",
            trigger: "change",
          },
        ],
        optionList: [
          {
            label: "串口",
            value: "串口",
          },
          {
            label: "BLE",
            value: "BLE",
          },
          {
            label: "2/3/4G",
            value: "2/3/4G",
          },
          {
            label: "WIFI",
            value: "WIFI",
          },
          {
            label: "NB",
            value: "NB",
          },
          {
            label: "LoRa",
            value: "LoRa",
          },
        ],
      },
      {
        key: "productId",
        type: "select",
        label: "所属产品",
        placeholder: "请选择所属产品",
        validate: [
          {
            required: true,
            message: "请选择所属产品",
            trigger: "change",
          },
        ],
        optionList: productList,
      },
    ],
    handelFormShow: (name, flag) => {
      crudData.value.form.formName = name;
      crudData.value.form.formShow = flag;
    },
    handelSubmit: (data) => {
      let queryData = {
        ...data,
      };
      queryData.address = Number(data.address);
      if (crudData.value.form.formName != "添加") {
        queryData.id = editId.value;
      }
      proxy
        ._http({
          url: "/api/equipment/addOrUpdate",
          type: "post",
          isBody: true,
          isLoading: true,
          data: queryData,
        })
        .then((res) => {
          ElMessage.success(
            crudData.value.form.formName == "添加" ? "添加成功" : "编辑成功"
          );
          getTableData();
          //此处需要在使用完data后，再将弹窗关闭，否则data数据将被重置
          crudData.value.form.formShow = false;
        })
        .catch((err) => {
          //此处需要在使用完data后，再将弹窗关闭，否则data数据将被重置
          crudData.value.form.formShow = false;
        });
    },
  },
  //查询参数回调
  searchCb: (e) => {
    console.log("searchCb", e);
    getTableData(e);
  },
  //重置回调
  reset: (e) => {
    console.log("reset", e);
    getTableData();
  },
});

const getProductList = () => {
  proxy
    ._http({
      url: "/api/product/page",
      type: "post",
      isBody: true,
      isLoading: true,
      data: {
        page: 1,
        pageSize: 999999,
      },
    })
    .then((res) => {
      console.log(999, res);
      if (Array.isArray(res.records)) {
        productList.value = res.records.map((item) => {
          return {
            label: item.productName,
            value: item.id,
          };
        });
      }
    })
    .catch((err) => {});
};
getProductList();


const handleFileDownload=(blob,response) =>{
  // 1. 从响应头获取文件名（仅处理ASCII文件名）
  let fileName = 'default.pdf';
  const contentDisposition = response.headers.get('Content-Disposition');
  
  if (contentDisposition) {
    const match = contentDisposition.match(/filename=([^;\n]+)/);
    if (match) fileName = match[1].replace(/['"]/g, '');
  }

  // 2. 创建下载链接
  const link = document.createElement('a');
  link.href = window.URL.createObjectURL(new Blob([blob]));
  link.download = fileName;
  
  document.body.appendChild(link);
  link.click();
  
  // 3. 清理资源
  document.body.removeChild(link);
  window.URL.revokeObjectURL(link.href);
  // const link = document.createElement('a');
  // const url = window.URL.createObjectURL(new Blob([blob]));

  // link.href = url;
  // link.setAttribute('download','imx6ull.pdf');// 设置下载的文件名和格式
  // document.body.appendChild(link);
  // link.click();

  // // 清除链接
  // link.parentNode.removeChild(link);
  // window.URL.revokeObjectURL(url);//释放内存
};

const getTableData = (e) => {
  console.log("getTableData", e);
  let queryData = {
    page: crudData.value.pager.pageIndex,
    pageSize: crudData.value.pager.pageSize,
    equipmentName: (e && e.equipmentName) || null,
    netType: (e && e.netType) || null,
    startTime:
      e && e.createTime && e.createTime.length ? e.createTime[0] : null,
    endTime: e && e.createTime && e.createTime.length ? e.createTime[1] : null,
  };
  for (let item in queryData) {
    if (queryData[item] == null) {
      delete queryData[item];
    }
  }
  proxy
    ._http({
      url: "/api/equipment/page",
      type: "post",
      isBody: true,
      isLoading: true,
      data: queryData,
    })
    .then((res) => {
      console.log(999, res);
      crudData.value.data = Array.isArray(res.records) ? res.records : [];
      crudData.value.pager.total = res.total || 0;
    })
    .catch((err) => {});
};

onMounted(() => {
  getTableData();
});

const uploadUrl = ref("/api/alarmPush/import");
var selectTion = reactive([]);
const getSelection = (val) => {
  selectTion = val;
  console.log("选中", selectTion);
};
</script>

<style lang="scss" scoped></style>
